# handle_report_data.py - Handle requests to report on the datastore.
# Copyright 2010 Rob Myers <rob@robmyers.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import datastore
import glob
import logging
import os
import reporting
import traceback
import yaml

from Cheetah.Template import Template

import wsgiref.handlers
from google.appengine.ext import webapp

class ReportDataWorker(webapp.RequestHandler):
    def get(self):
        try:
            html = file('./templates/report.html').read()
            template = Template(html)
            yaml_file_text = file('./config.yaml').read()
            config = yaml.safe_load(yaml_file_text)
            dgrs_path = config.get('path_to_dgrs', './dgrs')
            template.dgr_yamls = glob.glob (os.path.join (dgrs_path, '*.yaml'))
            self.response.out.write(template)
        except Exception, e:
                logging.error(type(e))
                logging.error(str(e))
                logging.error(traceback.format_exc())

    def post(self):
        try:
            which_dgr = self.request.get('dgr_yaml')
            formatter = reporting.XmlFormatter(self.response.out)
            if which_dgr == 'All':
                reporting.report_dump(formatter)
            else:
                reporting.report_dgr(formatter, which_dgr)
                
        except Exception, e:
            logging.error(type(e))
            logging.error(str(e))
            logging.error(traceback.format_exc())

def main():
    wsgiref.handlers.CGIHandler().run(webapp.WSGIApplication([
                ('/report-data', ReportDataWorker)], debug=True))
    
if __name__ == '__main__':
    logging.getLogger().setLevel(logging.DEBUG)
    main()
